package com.lecyon.farm.handler;

import com.lecyon.farm.base.RestResponse;
import com.lecyon.farm.common.constant.CommonConstant;
import com.lecyon.farm.util.ResultUtil;
import com.lecyon.farm.util.StringHelper;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.ShiroException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;

/**
 * @author Yao Zheng
 * @Date 2019/7/30 16:28
 */
@RestControllerAdvice
public class BindExceptionHandler {

    private static Logger logger = LoggerFactory.getLogger(BindExceptionHandler.class);

    /**
     * 自定义异常的统一处理
     *
     * @param ex 自定义的异常
     * @return result
     */
    @ExceptionHandler(Exception.class)
    public RestResponse handleBindException(MethodArgumentNotValidException ex) {
        logger.error("拦截异常-", ex);
        BindingResult bindingResult = ex.getBindingResult();
        StringBuffer errorMessage = new StringBuffer(bindingResult.getFieldErrors().size() * 16);
        List<FieldError> fieldErrorList = bindingResult.getFieldErrors();
        if (CollectionUtils.isNotEmpty(fieldErrorList)) {
            fieldErrorList.forEach(item -> {
                if (StringHelper.isNotEmpty(item.getDefaultMessage())) {
                    errorMessage.append(item.getDefaultMessage());
                }
            });
        }
        // 生成返回结果
        RestResponse errorResult = new RestResponse();
        errorResult.setCode(CommonConstant.EX_FORM_VALIDATE_ERROR);
        errorResult.setErrorMessage(errorMessage.toString());
        errorResult.setCurrentTime(LocalDateTime.now(ZoneId.systemDefault()));
        return errorResult;
    }

    /**
     * 权限相关异常的统一处理
     *
     * @param e 权限相关异常
     * @return result
     */
    @ExceptionHandler(ShiroException.class)
    @ResponseBody
    public RestResponse doHandleShiroException(ShiroException e) {
        RestResponse result = new RestResponse();
        result.setCurrentTime(LocalDateTime.now(ZoneId.systemDefault()));
        return ResultUtil.error(result, CommonConstant.EX_CLIENT_FORBIDDEN, "没有相应的权限执行此操作");
    }

    /**
     * 参数接收异常处理
     * JSON convert exception
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseBody
    public RestResponse handleHttpMessageNotReadableException(HttpMessageNotReadableException ex) {
        RestResponse response = new RestResponse();
        response.setCode(22);
        response.setErrorMessage(CommonConstant.JSON_CONVERT_ERROR_MESSAGE);
        response.setCurrentTime(LocalDateTime.now(ZoneId.systemDefault()));
        return response;
    }
}
